package com.zhiyou100.review.day020.homework;

import cn.hutool.core.util.RandomUtil;

/**
 * @packageName: Homework04
 * @className: com.zhiyou100.review.day020.homework
 * @Description: TODO 创建一个Demo类  属性animalName动物名字和foodName食物名字 一个线程循环的给demo对象的animalName和foodName赋值  (狗:骨头   猴:香蕉) 一个线程循环的打印：拿xx喂xx  不要出现拿香蕉喂狗的情况
 * @author: yang
 * @date: 7/1/20
 */
public class Homework04 {
    public static void main(String[] args) {
        Demo demo = new Demo();
        Thead1 thead1 = new Thead1(demo);
        Thead2 thead2 = new Thead2(demo);
        new Thread(thead1).start();
    }
}

class Demo {
    private String animalName;
    private String foodName;

    public Demo() {
    }

    public String getAnimalName() {
        return animalName;
    }

    public void setAnimalName(String animalName) {
        this.animalName = animalName;
    }

    public String getFoodName() {
        return foodName;
    }

    public void setFoodName(String foodName) {
        this.foodName = foodName;
    }

    public Demo(String animalName, String foodName) {
        this.animalName = animalName;
        this.foodName = foodName;
    }
}

class Thead1 implements Runnable {
    public Thead1(Demo demo) {
        this.demo = demo;
    }

    private Demo demo;

    public Demo getDemo() {
        return demo;
    }

    public void setDemo(Demo demo) {
        this.demo = demo;
    }

    /**
     * @Description: TODO 设置方法
     * @name: run
     * @param: []
     * @return: void
     * @date: 7/1/20 20:07
     * @author: yang
     */
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {

            synchronized (demo) {
                boolean b = RandomUtil.randomBoolean();
                // 随机一个 狗或者 猴子
                if (b) {
                    demo.setAnimalName("狗");
                    demo.setFoodName("骨头");
                } else {
                    demo.setAnimalName("猴");
                    demo.setFoodName("香蕉");
                }
                new Thread(new Thead2(demo)).start();
            }
        }
    }
}

class Thead2 implements Runnable {
    private Demo demo;

    /**
     * @Description: TODO 打印方法
     * @name: run
     * @param: []
     * @return: void
     * @date: 7/1/20 20:08
     * @author: yang
     */
    @Override
    public void run() {
        synchronized (demo) {
            String message = "拿" + demo.getFoodName() + " 喂 " + demo.getAnimalName();
            System.out.println(message);
        }
    }

    public Demo getDemo() {
        return demo;
    }

    public void setDemo(Demo demo) {
        this.demo = demo;
    }

    public Thead2(Demo demo) {
        this.demo = demo;
    }
}


